<?php
// +----------------------------------------------------------------------
// | Created by Sublime: [ Conqweal ]
// +----------------------------------------------------------------------
// | Copyright (c) 2021~20223[chenjia] All rights reserved.
// +----------------------------------------------------------------------
// | SiteUrl: http://www.99dn.cn
// +----------------------------------------------------------------------
// | Author: Conqweal <150672834@qq.com>
// +----------------------------------------------------------------------
// | Date: 2021/12/22 0026
// +----------------------------------------------------------------------
// | Description:用户管理
// +----------------------------------------------------------------------

namespace app\admin\controller;
use app\BackendController;
use app\admin\model\User as cmodel;
use app\admin\model\UserCredit as creditModel;
use app\admin\model\UserCreditLog as creditLogModel;
use app\admin\model\UserProfile;
use support\Request;
use think\facade\Db;

class UserController extends BackendController
{

    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    function list() {
        $roles        = Db::name('role')->column('r_name', 'r_id');
        $default_role = '';
        return view("user/list", compact('roles', 'default_role'));
    }

    public function listData(Request $request)
    {
        $limit = $request->get("limit", 10);
        $q     = cmodel::alias("u")
            ->join("user_profile p", " u.u_id=p.u_id", "left")
            ->join('admin a', "a.u_id=u.u_id", 'left')
            ->join('user_credit c', "c.u_id=p.u_id", 'left')
        ;
        if ($request->get('role')) {
            $q->join("role_user ru", "ru.u_id=u.u_id", "left")->where("ru.r_id", $request->get('role'));
        }
        $request->get('id') && $q->where('u.u_id', $request->get('id'));
        $request->get('username') && $q->where('u.username', 'like', '%' . $request->get('username') . '%');
        $request->get('email') && $q->where('u.email', 'like', '%' . $request->get('email') . '%');
        $request->get('phone') && $q->where('u.phone', 'like', '%' . $request->get('phone') . '%');
        $request->get('sex') && $q->where('u.sex', $request->get('sex'));
        $q->order("u_id", "desc");
        $ls = $q->field("u.*,p.truename,p.avatar,c.level as credit_level,c.integral as credit_integral")->paginate(['list_rows' => $limit, 'request' => request()->all()]);
        
        foreach ($ls as $k => $v) {
            $v->sex_text         = $v->sex_text;
            $v->status_text      = $v->status_text;
            $v->credit_level_txt = $v->credit_level ? __(\app\admin\model\UserCredit::creditLevel($v->credit_level)[0]) : '';
            $ls[$k]              = $v;
        }

        return json(['code' => $ls->total() > 0 ? 0 : 201, 'msg' => '无数据', 'count' => $ls->total(), 'data' => $ls->items()]);
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function myProfile()
    {
        $data       = cmodel::find(session("admin_id"));
        $role_names = [];
        foreach ($data->roles as $item) {
            $role_names[] = $item->role->r_name;
        }
        $role_names = implode(",", $role_names);
        $remarks    = isset($data->profile->info) ? $data->profile->info['remarks'] : '';
        $sexs       = [1 => '男', 2 => '女'];
        return view('user/myProfile', compact("data", "remarks", 'sexs', 'role_names'));
    }

    public function saveMyProfile(Request $request)
    {

        $post    = $request->post();
        $session = $request->session();

        $post['u_id'] = $session->get("admin_id");

        $validate = new \app\admin\validate\User;

        $result = $validate->scene('saveMyProfile')->check($post);

        if (!$result) {
            $data = ['msg' => $validate->getError(), 'status' => -1];
        } else {
            $cmodel = new cmodel();
            $cmodel->where('u_id', session("admin_id"))->save($post);
            $profile         = new UserProfile();
            $t               = $profile->where('u_id', session("admin_id"))->find();
            $info            = isset($t->info) ? $t->info : [];
            $info['remarks'] = $post['remarks'];
            $profile_post    = ['avatar' => $post['avatar'], 'nickname' => $post['nickname'], 'info' => $info, 'u_id' => session("admin_id")];

            $t ? $t->save($profile_post) : $profile->save($profile_post);
            $data = ["code" => 0, 'msg' => '保存成功', 'status' => 1];
        }

        return json($data);
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        $data['sex']  = 1;
        $data['role'] = 0;
        $roles        = Db::name('role')->column('r_name', 'r_id');
        return view('user/create', compact('data', 'roles'));
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $post = $request->post();
        if ($post['password']) {
            $post['password'] = encrypt($post['password']);
        }
        $validate = new \app\admin\validate\User;
        $result   = $validate->check($post);
        if (!$result) {
            $data = ['code' => 0, 'msg' => $validate->getError(), 'status' => -1];
        } else {
            $cmodel = new cmodel();
            $cmodel->save($post);
            $id = $cmodel->u_id;
            if ($post['roles']) {
                $roles_tmp = $post['roles'];
                $roles;
                foreach ($roles_tmp as $v) {
                    $roles[] = ['r_id' => $v, 'u_id' => $id];
                }
                //关联模型保存
                $cmodel->roles()->saveAll($roles);
            }

            $profile      = new UserProfile();
            $profile_post = ['avatar' => $post['avatar'], 'truename' => $post['truename'], 'u_id' => $id];
            $profile->save($profile_post);
            $data = ['code' => 0, 'msg' => '添加成功', 'status' => 1];
        }
        return json($data);

    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit(Request $request)
    {
        $id         = $request->get("id");
        $data       = cmodel::find($id);
        $data->role = $data->roles()->column('r_id');
        $roles      = Db::name('role')->column('r_name', 'r_id');
        return view("user/edit", compact('data', 'roles'));
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request)
    {
        $id   = $request->get("id");
        $post = $request->post();

        $toekn_del = 0;
        if ($post['password']) {
            $post['password'] = encrypt($post['password']);
            $toekn_del        = 1;
        } else {
            unset($post['password']);
        }
        $validate = new \app\admin\validate\User;
        $result   = $validate->scene('editProfile')->check($post);
        if (!$result) {
            $data = ['code' => 0, 'msg' => $validate->getError(), 'status' => -1];
        } else {
            $cmodel = cmodel::find($id);
            $cmodel->save($post);
            $roles_tmp = $post['roles'];
            $roles;
            foreach ($roles_tmp as $v) {
                $roles[] = ['r_id' => $v, 'u_id' => $id];
            }
            //关联模型保存
            $cmodel->roles()->where('u_id', $id)->delete();
            $cmodel->roles()->saveAll($roles);
            $profile      = new UserProfile();
            $t            = $profile->where('u_id', $id)->find();
            $profile_post = ['avatar' => $post['avatar'], 'truename' => $post['truename'], 'u_id' => $id];

            $t ? $t->save($profile_post) : $profile->save($profile_post);
            if ($toekn_del == 1) {
                Db::name("user_token")->where("u_id", $id)->delete();
            }
            $data = ['code' => 0, 'msg' => '修改成功', 'status' => 1];
        }
        return json($data);
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete(Request $request)
    {
        $id = $request->get("id");
        cmodel::where('u_id', 'in', $id)->update(['status' => 0]);
        $data = ['msg' => '禁用成功', 'status' => 1];
        return json($data);
    }

    public function changePass()
    {
        $admin_id = session("admin_id");

        return view('user/change_pass');

    }

    public function saveChangePass(Request $req)
    {
        $data = ['code' => 0, 'status' => 1, 'msg' => '保存成功'];

        $admin_id = session("admin_id");
        $password = $req->post("password");
        cmodel::whereRaw("u_id=:id", ['id' => $admin_id])->save(['password' => encrypt($password)]);
        return json($data);
    }

    public function creditLog()
    {
        $request   = $this->request;
        $types     = creditModel::creditBasic();
        $new_types = [];
        array_walk($types, function ($v, $k) use (&$new_types) {
            $new_types[$k] = $v[0];
        });
        $default_type = '';
        return view('credit_log', compact('new_types', 'default_type'));
    }

    public function creditLogData()
    {
        $request = request();
        $limit   = $request->get("limit", 10);
        $q       = creditLogModel::alias("a")
            ->join("user b", " a.u_id=b.u_id")
            ->join("user_profile p", " p.u_id=a.u_id", "left");
        $request->get('u_id') && $q->where('a.u_id', $request->get('u_id'));
        $request->get('type') && $q->where('a.type', $request->get('type'));
        $q->order("id", "desc");
        $ls    = $q->field("a.*,b.username,p.avatar")->paginate(['list_rows' => $limit, 'request' => request()->all()]);
        $total = $ls->total();
        $types = creditModel::creditBasic();
        $items = $ls->items();
        $items = array_map(function ($v) use ($types) {
            $v->type_txt = $types[$v->type][0];
            return $v;
        }, $items);
        return json(['code' => $total > 0 ? 0 : 201, 'msg' => '无数据', 'count' => $total, 'data' => $items]);
    }

}
